<?php
// 对购物车操作
class cartControl extends Control{
	// 实例化出一个购物车
	public function __init(){
		// $_SESSION=array();
		if(!isset($_SESSION['cart'])){
			// session_start();
			$_SESSION['cart']=array();
			$_SESSION['cart']['goods']=array();//放库存的id
			$_SESSION['cart']['totalprice']=0;//统计库存总的价格
			$_SESSION['cart']['totalnum']=0;//统计库存总的数量	
		}
	}
	// 购物车订单默认显示的页面
	public function index(){
		// p($_SESSION);
		// print_const();
		// p($_SERVER);die;
		// P($_SESSION);
		// 循环购物车里面的商品，商品的建就是库存id,通过库存的id我们就可以查到具体的商品，然后再把库存的具体的信心压到商品里面去
		if(!empty($_SESSION['cart']['goods'])){
			foreach($_SESSION['cart']['goods'] as $stid=>$stockData){
				$stock=M("stock")->where(array("st_id"=>$stid))->find();
				$goods[$stid]=M("goods")->where(array("gid"=>$stock['goods_gid']))->find();
				// p($goods);die;
				$stockData['stid']=$stid;
				$goods[$stid]['stockData']=$stockData;
				// $goods[$stid]['stockData']['stid']=$stid;
				// p($goods);die;
			}	
			// p($goods);
		$goods=array_reverse($goods);//返回顺序相反的数组
		$this->assign("session",$_SESSION['cart']);
		$this->assign("goods",$goods);
		}
		
		//分配购物车
		$this->assign("cart",cart());
		$this->display('cartlist');
	}

// 往购车里面添加商品
	public function addCart(){
		// p(1);
	// session_unset();	
		// p(Q(""));
		// p(1);
		$stid=Q("stid",0,'intval');
		if(!$stid)exit;
		// $stid=1;
		$price=Q("price");
		$num=Q("num");
		// p($price);
		// if(!$stid){
		// 	return;
		// }
		if(!isset($_SESSION['cart']['goods'][$stid])){
			//说明以前没有收藏过这个产品
			$_SESSION['cart']['goods'][$stid]=array("num"=>$num,"price"=>$price);
		}else{
			$_SESSION['cart']['goods'][$stid]['num']=$_SESSION['cart']['goods'][$stid]['num']+$num;
		}
			$_SESSION['cart']['totalnum']=0;
			$_SESSION['cart']['totalprice']=0;
		foreach($_SESSION['cart']['goods'] as $stock){
			$_SESSION['cart']['totalnum']+=$stock['num'];
			$_SESSION['cart']['totalprice']+=$stock['num']*$stock['price'];
		}
		$this->assign("categoryInfo",category());
		//分配热门搜索
		$this->assign("hot",hot());
		//分配购物车里面的商品
		$this->assign("cart",cart());
		$this->display("addcart");
	}


	// 删除购物车里面的库存
	function del(){
		// p(Q("stid"));
		$stid=Q('stid');
		// p($_SESSION['cart']);
		foreach($_SESSION['cart']['goods'] as $k=>$v){
			if($k==$stid){
				unset($_SESSION['cart']['goods'][$stid]);
			}
		}
		// 从新计算总数量和总价格
			$_SESSION['cart']['totalnum']=0;
			$_SESSION['cart']['totalprice']=0;

			foreach($_SESSION['cart']['goods'] as $stock){
			$_SESSION['cart']['totalnum']+=$stock['num'];
			$_SESSION['cart']['totalprice']+=$stock['num']*$stock['price'];
		}
		go(U("index"));
	}



}















